package com.brommko.android.universalwebview;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.brommko.android.universalwebview.util.NetworkHandler;
import com.brommko.android.universalwebview.util.PermissionUtil;
import com.brommko.android.universalwebview.util.ProgressDialogHelper;
import com.brommko.android.universalwebview.util.UrlHander;
import com.google.android.gms.ads.AdView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main2Activity extends AppCompatActivity implements View.OnClickListener, DownloadListener, SwipeRefreshLayout.OnRefreshListener {

    /* URL saved to be loaded after fb login */
    public static String target_url, target_url_prefix;


    public WebView mWebview;
    public ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public String mCameraPhotoPath;
    public Uri mCapturedImageURI = null;
    public static final int FILE_CHOOSER_RESULT_CODE = 1;
    public static final int REQUEST_SELECT_FILE = 2;

    public FrameLayout mContainer;
    private ImageView mImageViewSplash;
    private ImageView mBack;
    private ImageView mForward;
    private SwipeRefreshLayout mSwipeToRefresh;
    public boolean show_content = true, showToolBar = true;


    private AdView mAdView;
    public String urlData, currentUrl, contentDisposition, mimeType;
    private AdMob admob;

    //DATA FOR GEOLOCAION REQUEST
    String geoLocationOrigin;
    GeolocationPermissions.Callback geoLocationCallback;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (TextUtils.isEmpty(getString(R.string.pullToRefresh))){
            setContentView(R.layout.content_main);
        } else {
            setContentView(R.layout.content_main_pull_to_refresh);
        }
        checkURL(getIntent());
        initComponents();
        initBrowser(savedInstanceState);


        if (savedInstanceState != null) {
            showContent();
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    showContent();
                }
            }, 5000);
        }
    }

    private void checkURL(Intent intent) {
        if (intent != null) {
            if ("text/plain".equals(intent.getType()) && !TextUtils.isEmpty(intent.getStringExtra(Intent.EXTRA_TEXT))) {
                target_url = intent.getStringExtra(Intent.EXTRA_TEXT);
                target_url_prefix = Uri.parse(target_url).getHost();
                currentUrl = target_url;
                return;
            }
        }

        target_url = getString(R.string.target_url);

        if (TextUtils.isEmpty(target_url)) {
            target_url = "file:///android_asset/index.html";
            target_url_prefix = "android_asset";
        } else {
            target_url_prefix = Uri.parse(target_url).getHost();
        }

        currentUrl = target_url;

        if (mWebview != null) {
            mWebview.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        SuperViewWeb.activityResumed();
        hideStatusBar();
        checkURL(getIntent());
    }

    @Override
    protected void onPause() {
        super.onPause();
        SuperViewWeb.activityPaused();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebview.saveState(outState);
    }
    private void removeAds() {
        mAdView.setVisibility(View.GONE);
        if (admob != null) {
            admob.stopRepeatingTask();
        }
    }

    private void initComponents() {
        mAdView = (AdView) findViewById(R.id.adView);
        mSwipeToRefresh= (SwipeRefreshLayout) findViewById(R.id.swipeToRefresh);
        if (mSwipeToRefresh != null) {
            mSwipeToRefresh.setOnRefreshListener(this);
        }
        mImageViewSplash = (ImageView) findViewById(R.id.image_splash);


        if (TextUtils.isEmpty(getString(R.string.toolbar))) {
            showToolBar = false;
        }

        if (showToolBar) {
            mBack = (ImageView) findViewById(R.id.back);
            mForward = (ImageView) findViewById(R.id.forward);
            ImageView mRefresh = (ImageView) findViewById(R.id.refresh);

            mBack.setOnClickListener(this);
            mForward.setOnClickListener(this);
            mRefresh.setOnClickListener(this);
        } else {
            LinearLayout llToolbarContainer = (LinearLayout) findViewById(R.id.toolbar_footer);
            if (llToolbarContainer != null) {
                llToolbarContainer.setVisibility(View.GONE);
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mAdView.getLayoutParams();
                lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            }
        }
    }

    public void hideStatusBar() {
        if (!TextUtils.isEmpty(getString(R.string.hide_status_bar))) {
            if (Build.VERSION.SDK_INT < 16) {
                getWindow().setFlags(
                        WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            } else {
                View decorView = getWindow().getDecorView();
                int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
                decorView.setSystemUiVisibility(uiOptions);
                ActionBar actionBar = getActionBar();
                if (actionBar != null) {
                    actionBar.hide();
                }
            }
        }
    }

    public void showContent() {
        if (show_content) {
            PermissionUtil.checkPermissions(this, new String[]{android.Manifest.permission.RECORD_AUDIO,
                    android.Manifest.permission.CALL_PHONE,
                    android.Manifest.permission.SEND_SMS,
                    android.Manifest.permission.ACCESS_NETWORK_STATE,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    android.Manifest.permission.BLUETOOTH,
                    android.Manifest.permission.ACCESS_FINE_LOCATION,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION,
                    android.Manifest.permission.INTERNET
            });

            show_content = false;
            admob = new AdMob(this, mAdView);
            admob.requestAdMob();
            mImageViewSplash.setVisibility(View.GONE);
            mContainer.setVisibility(View.VISIBLE);
            ProgressDialogHelper.dismissProgress();
        }
    }

//    @SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled"})
    private void initBrowser(Bundle savedInstanceState) {

        mWebview = (WebView) findViewById(R.id.webview);
        mContainer = (FrameLayout) findViewById(R.id.webview_frame);
        WebSettings webSettings = mWebview.getSettings();
        webSettings.setJavaScriptEnabled(true);

        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setGeolocationDatabasePath(getFilesDir().getPath());
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setUserAgentString(webSettings.getUserAgentString()+" Android");
        if (TextUtils.isEmpty(getString(R.string.cache))) {
            webSettings.setAppCacheEnabled(true);
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        int a = WebSettings.TextSize.SMALLER.ordinal();
        mWebview.setWebViewClient(new SuperWebViewClient(this));
        mWebview.setWebChromeClient(new SuperWebChromClient(this));
        mWebview.setDownloadListener(this);
        mWebview.addJavascriptInterface(new WebAppInterface(this, mWebview), "android");
        CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.setAcceptThirdPartyCookies(mWebview, true);
        } else {
            cookieManager.setAcceptCookie(true);
        }
        CookieManager.setAcceptFileSchemeCookies(true);
        if (Build.VERSION.SDK_INT >= 19) {
            mWebview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else if(Build.VERSION.SDK_INT >=15 && Build.VERSION.SDK_INT < 19) {
            mWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        if (!TextUtils.isEmpty(getString(R.string.zoom))) {
            mWebview.getSettings().setSupportZoom(true);
            mWebview.getSettings().setBuiltInZoomControls(true);
            mWebview.getSettings().setDisplayZoomControls(false);
        }
        if (savedInstanceState != null) {
            mWebview.restoreState(savedInstanceState);
        } else {
            mWebview.loadUrl(target_url);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (mWebview.canGoBack()) {
                    mWebview.goBack();
                }
                break;
            case R.id.forward:
                if (mWebview.canGoForward()) {
                    mWebview.goForward();
                }
                break;
            case R.id.refresh:
                mWebview.loadUrl(target_url);
                if (!show_content) {
                    ProgressDialogHelper.showProgress(Main2Activity.this);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILE_CHOOSER_RESULT_CODE || requestCode == REQUEST_SELECT_FILE ) {
            permissionSelectFile(requestCode, resultCode, data);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebview != null) {
            mWebview.destroy();
        }
        if (admob != null) {
            admob.stopRepeatingTask();
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebview.canGoBack()) {
            mWebview.goBack();
        } else {
            super.onBackPressed();
        }
    }

    //This method will be called when the user will tap on allow or deny
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //Checking the request code of our request
        if (requestCode == PermissionUtil.MY_PERMISSIONS_REQUEST_CALL) {
            //If permissionSelectFile is granted
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                UrlHander.call(Main2Activity.this, urlData);
            }
        } else if (requestCode == PermissionUtil.MY_PERMISSIONS_REQUEST_SMS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                UrlHander.sms(Main2Activity.this, urlData);
            }
        } else if (requestCode == PermissionUtil.MY_PERMISSIONS_REQUEST_DOWNLOAD) {
            UrlHander.download(Main2Activity.this, urlData, contentDisposition, mimeType);
        } else if (requestCode == PermissionUtil.MY_PERMISSIONS_REQUEST_GEOLOCATION) {
            if (geoLocationCallback != null) {
                geoLocationCallback.invoke(geoLocationOrigin, true, false);
            }
        }
    }

    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long l) {
        this.contentDisposition = contentDisposition;
        this.mimeType = mimeType;
        UrlHander.downloadLink(this, url, contentDisposition, mimeType);
    }

    public void setToolbarButtonColor() {
        if (showToolBar) {
            if (mWebview.canGoBack()) {
                mBack.setColorFilter(ContextCompat.getColor(this, R.color.colorPrimary));
            } else {
                mBack.setColorFilter(ContextCompat.getColor(this, R.color.gray));
            }
            if (mWebview.canGoForward()) {
                mForward.setColorFilter(ContextCompat.getColor(this, R.color.colorPrimary));
            } else {
                mForward.setColorFilter(ContextCompat.getColor(this, R.color.gray));
            }
        }
    }

    @Override
    public void onRefresh() {
        mWebview.reload();
        mSwipeToRefresh.setRefreshing(false);
    }




    public void permissionSelectFile(int requestCode, int resultCode, Intent data){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessage == null) {
                super.onActivityResult(requestCode, resultCode, data);
                return;
            }

            Uri[] results = null;

            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data, then we may have taken a photo
                    if (mCameraPhotoPath != null) {
                        results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }
                } else {
                    String dataString = data.getDataString();
                    if (dataString != null) {
                        results = new Uri[]{Uri.parse(dataString)};
                    }
                }
            }

            uploadMessage.onReceiveValue(results);
            uploadMessage = null;

        } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            if (requestCode != FILE_CHOOSER_RESULT_CODE || mUploadMessage == null) {
                super.onActivityResult(requestCode, resultCode, data);
                return;
            }

            if (requestCode == FILE_CHOOSER_RESULT_CODE) {

                if (null == this.mUploadMessage) {
                    return;

                }

                Uri result = null;

                try {
                    if (resultCode != RESULT_OK) {

                        result = null;

                    } else {

                        // retrieve from the private variable if the intent is null
                        result = data == null ? mCapturedImageURI : data.getData();
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "activity :" + e,
                            Toast.LENGTH_LONG).show();
                }

                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;

            }
        }
    }
}

